//Vuex使用方法：1.npm下载;2.创建store.js;3.创建仓储对象；4.导入到mian.js,挂载
// import { turn } from 'core-js/fn/array';
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);
var lsCart = JSON.parse(localStorage.getItem('cart') || '[]');
const store = new Vuex.Store({
    // namespaced: true,
    state:{//访问方式：this.$store.state
        cart:lsCart,
        //cart :[]

    },
    mutations:{
        addToCart(state,goods){
           var flag = false;
         
        state.cart.some(item =>{
            if(goods.id == item.id){
                item.count += parseInt(goods.count);
                flag = true;
                return true;
            }
        })
        if(!flag){
            state.cart.push(goods);
        }
        localStorage.setItem('cart',JSON.stringify(state.cart));
       },
       removeGoods(state,goodsId){
           state.cart = state.cart.filter(item =>{
               return item.id !=goodsId;
           })
           localStorage.setItem('cart',JSON.stringify(state.cart))
       },
       updateStore(state,goodsInfo){
           state.cart.some(item =>{
               if(item.id == goodsInfo.id){
                     item.count = goodsInfo.count
               }
           })
           //更新到本地存储，修改的数据
           if(state.cart.length >0){
               localStorage.setItem('cart',JSON.stringify(state.cart))
           }
       }
    },
    getters:{
        getTotalCount(state){
            var total =0;
            state.cart.forEach(item =>{
                total+=item.count;
            })
            return total;
        },
        getTotalPrice(state){
            var total = 0;
            state.cart.forEach(item =>{
                total += item.price * item.count;
                console.log(total)
            })
            return total;
        },

    }
})
export default store;